<?php

namespace Warehouse\Service;

use Inbound\Service\PublicInfoService;

class StockOutService {
    public $stockOut = NULL;
    public $stockIn = NULL;
    public $warehouseDeliveryorders = NULL;

    //查询记录总数
    public $count = 0;
    //页面展示包含页面样式
    public $page = 0;
    //数据
    public $relevant_data = array ();

    public $stockOut_data = array ();

    public $nowtime;

    /**
     * PurchaseordersService constructor.
     * @param string $table
     * @param array  $param
     */
    public function __construct ($table = '', $param = array ()) {
        $this->nowtime                 = date('Y-m-d H:i:s', time());
        $this->stockOut                = D('Warehouse/StockOut', 'Model');
        $this->stockIn                 = D('Warehouse/StockIn', 'Model');
        $this->warehouseDeliveryorders = D('Warehouse/WarehouseDeliveryorders', 'Model');
    }

    /**
     * @param $sku
     * 根据sku获取sku中文名   规格   储位
     */
    public function load_sku_info ($sku) {
        $position = M('storage_sku', 'wms_', 'fbawarehouse')
            ->where(array ('sku' => $sku))
            ->getField('id,storage_position');
        $position = array_filter($position);
        $sku_info = array (
            'sku_name'         => PublicInfoService::getSkuCnname_bak($sku),
            'sku_standard'     => PublicdataService::get_sku_standard($sku),
            'storage_position' => $position,
        );
        return $sku_info;
    }

    /**
     * 检测入库数量是否满足出库要求
     */
    public function check_warehouse_quantity ($array) {
        $data  = array ();
        $log   = '';
        $sites = PublicInfoService::get_site_array();
        foreach ($array as $key => $_array) {
            if (is_array($_array['storage_position'])) {
                foreach ($_array['storage_position'] as $position => $num) {
                    $_key = $_array['sku'].';'.$position.';'.$_array['site_id'].';'.$_array['enterprise_dominant'].';'.$_array['export_tax_rebate'];
                    if (!array_key_exists($_key, $data)) {
                        $data[$_key] = $num;
                    } else {
                        $data[$_key] += $num;
                    }
                }
            } else {
                $_key = $_array['sku'].';'.$_array['storage_position'].';'.$_array['site_id'].';'.$_array['enterprise_dominant'].';'.$_array['export_tax_rebate'];
                if (!array_key_exists($_key, $data)) {
                    $data[$_key] = $_array['quantity'];
                } else {
                    $data[$_key] += $_array['quantity'];
                }
            }
        }
        foreach ($data as $key => $val) {
            $conditions     = explode(';', $key);
            $find_condition = array (
                'sku'                 => $conditions['0'],
                'storage_position'    => $conditions['1'],
                'site_id'             => $conditions['2'],
                'enterprise_dominant' => $conditions['3'],
                'export_tax_rebate'   => $conditions['4'],
                'available_quantity'  => array (
                    'gt',
                    0
                )
            );
            $sku_total      = $this->get_total_available_quantity($find_condition);
            if ($sku_total < $val) {
                $export_tax_rebate = $conditions['4'] == 1?' 出口退税':' 非出口退税';
                $log .= '条件为：sku: '.$conditions['0'].' 储位: '.$conditions['1'].' 站点: '.$sites[$conditions['2']].
                    ' 公司主体:'.PublicInfoService::getCompanyName($conditions['3']).$export_tax_rebate.
                    ', 当前可用入库单可用量之和小于当前出库量之和'."<br/>";
            }elseif ($val <=0){
                $export_tax_rebate = $conditions['4'] == 1?' 出口退税':' 非出口退税';
                $log .= '条件为：sku: '.$conditions['0'].' 储位: '.$conditions['1'].' 站点: '.$sites[$conditions['2']].
                    ' 公司主体:'.PublicInfoService::getCompanyName($conditions['3']).$export_tax_rebate.
                    ', 出库量不能小于等于0'."<br/>";
            }
        }
        if ($log == '') {
            return array ('status' => 200);
        } else {
            return array (
                'status' => 403,
                'msg'    => $log
            );
        }
    }

    /**
     * @param      $array
     * @param null $model
     * @return mixed
     * 新建特殊出库单
     */
    public function create_deliveryorders ($array, $flag = TRUE, &$model = NULL) {
        $res = $this->check_warehouse_quantity($array);
        if ($res['status'] == 200) {
            $model    = $model == NULL?$this->stockOut->model:$model;
            $data_all = array ();
            $i        = 0;
            foreach ($array as $key => $_array) {
                $stockOutdata = array (
                    'warehouseid'         => 102,
                    'crontrigger'         => 0,
                    'delivery_date'       => $this->nowtime,
                    'op_time'             => $_array['op_time'],
                    'delivery_department' => $_array['delivery_department'],
                    //帐号 需要将帐号名转换成
                    'delivery_man'        => $_array['delivery_man'],
                    //操作人
                    'sku'                 => $_array['sku'],
                    'sku_name'            => $_array['sku_name'],
                    'sku_standard'        => $_array['sku_standard'],
                    'storage_position'    => $_array['storage_position'],
                    'quantity'            => $_array['quantity'],

                    'internationalship_cost' => $_array['internationalship_cost'],
                    'remark'                 => $_array['remark'],
                    'type'                   => $_array['type'],
                    'site_id'                => $_array['site_id'],
                    //正常为10
                    'shipmentid'             => $_array['shipmentid'],
                    'package_box_id'         => $_array['package_box_id'],
                    'fnsku'                  => $_array['fnsku'],
                    'hs_code'                => $_array['hs_code'],
                    'declaration_element'    => $_array['declaration_element'],

                    'enterprise_dominant'    => $_array['enterprise_dominant'],
                    'export_tax_rebate'      => $_array['export_tax_rebate'],
                );
                //获取入库id 的条件
                $find_condition = array (
                    'sku'                    => $_array['sku'],
                    'storage_position'       => $_array['storage_position'],
                    'site_id'                => $_array['site_id'],
                    'enterprise_dominant'    => $_array['enterprise_dominant'],
                    'export_tax_rebate'      => $_array['export_tax_rebate'],
                    'available_quantity' => array (
                        'gt',
                        0
                    )
                );

                //2.获取所有可用入库id
                $warehouseorders_ids = $this->get_warehouseorders_id($find_condition);

                //4.循环可入库id   与  数量
                $change_info = $this->operate_id_quantity($_array['quantity'], $warehouseorders_ids);

                //3.计算当前出库单sku总价 money cost
                $price_info = $this->caculate_total_price($change_info);

                //6.插入到出库单表
                $stockOutdata['single_price']        = $price_info['cost'] / $_array['quantity'];
                $stockOutdata['money']               = $price_info['money'];
                $stockOutdata['cost']                = $price_info['cost'];
                $stockOutdata['supplier_id']         = $warehouseorders_ids[0]['supplier_id'];

                $this->stockOut_data = $stockOutdata;
                $this->stockOut->add_deliveryorders_table($this->stockOut_data, $model);

                //5.回写入库单中可用库存
                $this->update_available_quantity($this->stockOut->deliveryorders_id, $change_info, $model);

                //7.插入到对应关系表
                $this->add_warehouse_deliveryorders($stockOutdata['type'], $this->stockOut->deliveryorders_id, $_array['sku'], $change_info, $model);
                $this->warehouseDeliveryorders->warehouse_deliveryorders_id;

                if ($this->stockOut->deliveryorders_id && $this->warehouseDeliveryorders->warehouse_deliveryorders_id) {
                    //8.事务提交
                    $model->commit();
                    if ($flag) {
                        $i ++;
                    } else {
                        $data       = array (
                            'error'             => 0,
                            'deliveryorders_id' => $this->stockOut->deliveryorders_id
                        );
                        $data_all[] = $data;
                        return $data_all;
                    }
                } else {
                    $model->rollback();
                }
            }
            //
            if ($i == count($array)) {
                return array (
                    array (
                        'status' => '200',
                        'msg'    => '成功创建'.$i.'条出库单'
                    )
                );
            }
        } else {
            return $res['msg'];
        }
    }

    /**
     * @param      $array
     * @param null $model
     * @return mixed
     * 捡货单生成 出库单 接口
     */
    public function create_deliveryorders_by_picking_list ($array, &$model = NULL) {
        $res = $this->check_warehouse_quantity($array);
        if ($res['status'] == 200) {
            $model    = $model == NULL?$this->stockOut->model:$model;
            $data_all = array ();
            $log = '';
            foreach ($array as $_array) {
                $stockOutdata = array (
                    'warehouseid'         => 102,
                    'crontrigger'         => 0,
                    'delivery_date'       => $this->nowtime,
                    'op_time'             => $_array['op_time'],
                    'delivery_department' => $_array['delivery_department'],
                    //帐号 需要将帐号名转换成
                    'delivery_man'        => $_array['delivery_man'],
                    'seller_id'           => $_array['seller_id'],
                    //操作人
                    'sku'                 => $_array['sku'],
                    'sku_name'            => $_array['sku_name'],
                    'sku_standard'        => $_array['sku_standard'],
                    'storage_position'    => $_array['storage_position'],
                    'quantity'            => $_array['quantity'],

                    'internationalship_cost' => $_array['internationalship_cost'],
                    'remark'                 => $_array['remark'],
                    'type'                   => $_array['type'],
                    'site_id'                => $_array['site_id'],
                    //正常为10
                    'shipmentid'             => $_array['shipmentid'],
                    'package_box_id'         => $_array['package_box_id'],
                    'fnsku'                  => $_array['fnsku'],
                    'hs_code'                => $_array['hs_code'],
                    'declaration_element'    => $_array['declaration_element'],
                    'export_tax_rebate'      => $_array['export_tax_rebate'],
                    'enterprise_dominant'    => $_array['enterprise_dominant'],
                );
                //获取入库id 的条件
                if (is_array($_array['storage_position'])) {
                    $relevantData     = array ();
                    $storage_position = '';
                    foreach ($_array['storage_position'] as $position => $quantity) {
                        //一个出库单关联多储位
                        $find_condition = array (
                            'sku'                    => $_array['sku'],
                            'storage_position'       => $position,
                            'site_id'                => $_array['site_id'],
                            'enterprise_dominant'    => $_array['enterprise_dominant'],
                            'export_tax_rebate'      => $_array['export_tax_rebate'],
                            'available_quantity' => array (
                                'gt',
                                0
                            )
                        );
                        $storage_position .= $position.',';

                        //2.获取当前储位所有可用入库id
                        $warehouseorders_ids = $this->get_warehouseorders_id($find_condition);

                        //4.循环可入库id   与  数量
                        $change_info = $this->operate_id_quantity($quantity, $warehouseorders_ids);

                        //3.计算当前出库单sku总价 money cost
                        $price_info = $this->caculate_total_price($change_info);

                        //5.回写入库单中可用库存
                        $this->update_available_quantity('', $change_info, $model);

                        //6.对应关系表 插入数据
                        $data         = $this->warehouse_deliveryorders_data($_array['sku'], $change_info);
                        $relevantData = array_merge($data, $relevantData);
                    }
                    //7.插入到出库单表
                    $stockOutdata['single_price']     = $price_info['cost'] / $_array['quantity'];
                    $stockOutdata['money']            = $price_info['money'];
                    $stockOutdata['cost']             = $price_info['cost'];
                    $stockOutdata['supplier_id']      = $warehouseorders_ids[0]['supplier_id'];
                    $stockOutdata['storage_position'] = $storage_position;
                    $this->stockOut_data = $stockOutdata;
                    $this->stockOut->add_deliveryorders_table($this->stockOut_data, $model);

                    //8.插入到对应关系表
                    $res = $this->addAll_warehouse_deliveryorders($this->stockOut->deliveryorders_id, $relevantData, $model);
                    if ($this->stockOut->deliveryorders_id && $res) {
                        $model->commit();
                        $data     = array ($_array['fnsku'] => $this->stockOut->deliveryorders_id);
                        $data_all = array_merge($data, $data_all);
                    } else {
                        $model->rollback();
                    }
                } else {
                    $log .= $_array['sku'].'对应的储位不是数组<br/>';
                }
            }
            //9.返回
            if (count($data_all) == count($array) && $log == '') {
                return $msg = array (
                    'status'  => 200,
                    'message' => $data_all
                );
            } else {
                return $msg = array (
                    'status'  => 400,
                    'message' => $log
                );
            }
        } else {
            return $msg = array (
                'status'  => 400,
                'message' => $res['msg'],
            );
        }
    }


    /**
     * 循环操作
     * 计算当前出库单sku总价
     */
    public function operate_id_quantity ($quantity, $warehouseorders_ids) {
        $change_info   = array ();
        $temp_quantity = $quantity;
        foreach ($warehouseorders_ids as $id) {
            if ($temp_quantity > $id['available_quantity']) {
                $available_quantity_to = 0;
                $data                  = array (
                    'condition'  => array ('id' => $id['id']),
                    'data'       => array ('available_quantity' => $available_quantity_to),
                    'quantity'   => $id['available_quantity'],
                    'temp_money' => $id['single_price'] * $id['available_quantity'],
                    //入库单价*当前可用量
                    'temp_cost'  => $id['single_price'] * $id['available_quantity'] + $id['transportation_expense'] * $id['available_quantity'],
                    //入库单价*当前可用量+运费比重
                );
                $change_info[]         = $data;
                $temp_quantity -= $id['available_quantity'];
            } else {
                $available_quantity_to = $id['available_quantity'] - $temp_quantity;
                $data                  = array (
                    'condition'  => array ('id' => $id['id']),
                    'data'       => array ('available_quantity' => $available_quantity_to),
                    'quantity'   => $temp_quantity,
                    'temp_money' => $id['single_price'] * $temp_quantity,
                    //入库单价*当前可用量
                    'temp_cost'  => $id['single_price'] * $temp_quantity + $id['transportation_expense'] * $temp_quantity,
                    //入库单价*当前可用量+运费比重
                );
                $change_info[]         = $data;
                //当出库量小于当前出库id可用数量时  跳出循环
                break;
            }
        }
        return $change_info;
    }

    /**
     * @param $warehouseorders_ids
     * 计算当前出库单sku总价 money cost
     */
    public function caculate_total_price ($price_info) {
        $money = '';
        $cost  = '';
        foreach ($price_info as $price) {
            $money += $price['temp_money'];
            $cost += $price['temp_cost'];
        }
        $data = array (
            'money' => $money,
            'cost'  => $cost
        );
        return $data;
    }

    /**
     * @param $deliveryorders_id
     * @param $sku
     * @param $change_info
     * @param $model
     * 添加对应关系信息
     */
    public function add_warehouse_deliveryorders ($type, $deliveryorders_id, $sku, $change_info, $model) {
        foreach ($change_info as $info) {
            $this->relevant_data = array (
                'deliveryorders_id'  => $deliveryorders_id,
                'warehouseorders_id' => $info['condition']['id'],
                'sku'                => $sku,
                'quantity'           => $info['quantity'],
                'create_time'        => $this->nowtime,
            );
            $this->warehouseDeliveryorders->add_warehouse_deliveryorders($this->relevant_data, $model);
            if ($type == 50) {
                $this->create_unqualified_deal_invoices($this->relevant_data, $model);
            }
        }
    }

    /**
     * 不良品出库
     */
    public function create_unqualified_deal_invoices ($create_data, &$model = NULL) {
        $deliveryorders_info = $this->get_warehouseorders_id(array ('id' => $create_data['warehouseorders_id']));
        $arr                 = array (
            'warehouseid'         => 102,
            'crontrigger'         => 0,
            'invoice_date'        => $this->nowtime,
            'fail_deal_way'       => 0,
            'supplier_id'         => '',
            'check_remark'        => '',
            'end_remark'          => '',
            'deal_time'           => '',
            'end_time'            => '',
            'end_man'             => '',
            'status'              => 10,
            'purchase_man'        => '',
            //入库单可查询信息
            'deliveryorders_id'   => $create_data['deliveryorders_id'],
            'returned_parcel_id'  => $deliveryorders_info[0]['returned_parcel_id'] == ''?'':$deliveryorders_info[0]['returned_parcel_id'],
            'check_detail_id'     => $deliveryorders_info[0]['check_quality_detail_id'] == ''?'':$deliveryorders_info[0]['check_quality_detail_id'],
            //质检明细单id
            'purchaseorder_id'    => $deliveryorders_info[0]['purchaseorders_id'] == ''?'':$deliveryorders_info[0]['purchaseorders_id'],
            //采购员
            'store'               => $deliveryorders_info[0]['store'] == ''?'':$deliveryorders_info[0]['store'],
            'transfer_type'       => $deliveryorders_info[0]['transfer_type'] == ''?'':$deliveryorders_info[0]['transfer_type'],
            'supplier'            => $deliveryorders_info[0]['supplier_id'] == ''?'':$deliveryorders_info[0]['supplier_id'],
            'coupon_price'        => $deliveryorders_info['single_price'] == ''?'':$deliveryorders_info[0]['single_price'],
            //单价
            'return_cost'         => $deliveryorders_info[0]['transportation_expense'] * $create_data['quantity'],
            //运费

            //当前出库信息
            'sku'                 => $create_data['sku'],
            'quantity'            => $create_data['quantity'],
            'sku_name'            => $deliveryorders_info[0]['sku_name'] == ''?'':$deliveryorders_info[0]['sku_name'],
            'sku_standard'        => $deliveryorders_info[0]['sku_standard'] == ''?'':$deliveryorders_info[0]['sku_standard'],
            'storage_position'    => $deliveryorders_info[0]['storage_position'] == ''?'':$deliveryorders_info[0]['storage_position'],
            'export_tax_rebate'   => $deliveryorders_info[0]['export_tax_rebate'] == ''?'':$deliveryorders_info[0]['export_tax_rebate'],
            'enterprise_dominant' => $deliveryorders_info[0]['enterprise_dominant'] == ''?'':$deliveryorders_info[0]['enterprise_dominant'],
            'transfer_hopper_id'  => $deliveryorders_info[0]['transfer_hopper_id'] == ''?'':$deliveryorders_info[0]['transfer_hopper_id'],
            'site_id'             => $deliveryorders_info[0]['site_id']
        );
        //质检单信息
        $check_detail_info     = D('CheckQualityDetails', 'Model')->checkQualityDetails->where(array ('id' => $deliveryorders_info[0]['check_quality_detail_id']))
            ->field('check_man,remark,invoice_date')
            ->find();
        $arr['quality_man']    = $check_detail_info['check_man'] == ''?'':$check_detail_info['check_man'];
        $arr['quality_remark'] = $check_detail_info['remark'] == ''?'':$check_detail_info['remark'];
        $arr['check_time']     = $check_detail_info['check_time'] == ''?'':$check_detail_info['check_time'];

        //采购单信息
        $purchaseorder_info = D('PurchaseOrders', 'Model')->Purchaseorders->where(array ('id' => $deliveryorders_info[0]['purchaseorders_id']))
            ->field('purchase_id')
            ->find();
        $arr['operate_man'] = $purchaseorder_info['purchase_id'] == ''?'':$purchaseorder_info['purchase_id'];

        //插入到不良品入库表
        $UnqualifiedDealInvoices_model = D('UnqualifiedDealInvoices', 'Model');
        $UnqualifiedDealInvoices_model->add_unqualified_deal_invoices($arr, $model);
        //更新出库表信息
        $change_info = array (
            'condition' => array ('id' => $create_data['deliveryorders_id']),
            'data'      => array ('unqualified_deal_invoice_id' => $UnqualifiedDealInvoices_model->unqualified_deal_invoices_id),
        );

        $this->update_available_quantity($create_data['deliveryorders_id'], $change_info, $model);
    }

    /*
    * @param $deliveryorders_id
    * @param $sku
    * @param $change_info
    * @param $model
    * 添加对应关系信息
    */
    public function addAll_warehouse_deliveryorders ($deliveryorders_id, $relevantData, $model) {
        $data = array ();
        foreach ($relevantData as $info) {
            $this->relevant_data = array (
                'deliveryorders_id'  => $deliveryorders_id,
                'warehouseorders_id' => $info['warehouseorders_id'],
                'sku'                => $info['sku'],
                'quantity'           => $info['quantity'],
                'create_time'        => $info['create_time'],
            );
            $data[]              = $this->relevant_data;
        }
        return $this->warehouseDeliveryorders->addAll_warehouse_deliveryorders($data, $model);
    }

    /**
     * @param $deliveryorders_id
     * @param $sku
     * @param $change_info
     * @param $model
     * 对应关系表数据
     */
    public function warehouse_deliveryorders_data ($sku, $change_info) {
        $data = array ();
        foreach ($change_info as $info) {
            $this->relevant_data = array (
                'deliveryorders_id'  => '',
                'warehouseorders_id' => $info['condition']['id'],
                'sku'                => $sku,
                'quantity'           => $info['quantity'],
                'create_time'        => $this->nowtime,
            );
            $data[]              = $this->relevant_data;
        }
        return $data;
    }

    /**
     * @param $_array
     * 特殊出库
     */
    public function create_formate ($_array, $flag = TRUE) {
        //$supplier_info       = D('StockIn','Service')->get_supplier_by_sku(array('sku' => $_array['sku']));
        $data_info           = array ();
        $this->stockOut_data = array (
            'op_time'                => $this->nowtime,
            'delivery_man'           => $_SESSION['current_account']['id'],
            //操作人
            'sku'                    => strtoupper($_array['sku']),
            'sku_name'               => $_array['sku_name'],
            'sku_standard'           => $_array['sku_standard'],
            'storage_position'       => $_array['storage_position'],
            'quantity'               => $_array['quantity'],
            'type'                   => $_array['type'],
            'remark'                 => $_array['remark'],
            'site_id'                => $_array['site_id'],
            'export_tax_rebate'      => $_array['export_tax_rebate'],
            'enterprise_dominant'    => $_array['enterprise_dominant'],

            //先不做
            'internationalship_cost' => '',
            'delivery_department'    => '',
            //帐号 需要将帐号名转换成
            'shipmentid'             => '',
            'package_box_id'         => '',
            'fnsku'                  => '',
            'hs_code'                => '',
            'declaration_element'    => '',
        );
        $data_info[]         = $this->stockOut_data;
        return $this->create_deliveryorders($data_info, $flag);
    }

    /**
     * 根据sku获取入库单id
     */
    public function get_warehouseorders_id ($find_condition) {
        $warehouseorders_id = $this->stockIn->warehouseorders->where($find_condition)
            ->field('id,export_tax_rebate,enterprise_dominant,available_quantity,single_price,transportation_expense,
            warehouse_quantity,supplier_id,`purchaseorders_id`,`returned_parcel_id`,`check_quality_detail_id`,
            `sku_name`,`sku_standard`,`storage_position`,`store`,`transfer_hopper_id`,`transfer_type`,`site_id`')
            ->order('warehouse_date ASC')
            ->select();
        return $warehouseorders_id == ''?FALSE:$warehouseorders_id;
    }

    /*
    根据sku可用入库单  可用量之和
    */
    public function get_total_available_quantity ($find_condition) {
        $total_available_quantity = $this->stockIn->warehouseorders->where($find_condition)
            ->order('warehouse_date ASC')
            ->getField('sum(available_quantity)');
        return $total_available_quantity == ''?FALSE:$total_available_quantity;
    }

    /**
     * 回写可用库存  入库表
     */
    public function update_available_quantity ($deliveryorders_id, $change_info, &$model) {
        foreach ($change_info as $info) {
            $info['data']['deliveryorders_id'] = $deliveryorders_id;
            $res                               = $this->stockIn->update_warehouseorders($info['condition'], $info['data'], $model);
        }
        return $res;
    }

    /**
     * @param $datas
     * @return array
     * 检查上传数据的合法性
     */
    public function check_upload_data (&$datas) {
        $flag      = TRUE;
        $str       = '';
        $sites     = PublicInfoService::get_site_array();
        $sites_arr = array_flip($sites);
        foreach ($datas as $k => &$v) {
            if ($k == 1) {
                continue;
            }
            if ($v['A'] == '') {
                $flag = FALSE;
                $str .= '第'.$k.'行 出库类型 为空,导入失败'."<br/>";
            } else {
                $type = PublicdataService::get_deliveryorders_type_by_value(trim($v['A']));
                if ($type == '' || $type == 130 || $type == 150 || $type == 10) {
                    $flag = FALSE;
                    $str .= '第'.$k.'行 出库类型:'.trim($v['A']).' 不符合要求,导入失败'."<br/>";
                }
                $v['A'] = $type;
            }
            if ($v['B'] == '') {
                $flag = FALSE;
                $str .= '第'.$k.'行 SKU 为空,导入失败'."<br/>";
            }
            if ($v['C'] == '' || $v['C'] == 0) {
                $flag = FALSE;
                $str .= '第'.$k.'行 数量 为空或为0,导入失败'."<br/>";
            }
            if ($v['D'] == '') {
                $flag = FALSE;
                $str .= '第'.$k.'行 出库时间 为空,导入失败'."<br/>";
            } elseif (!$this->check_date_isValid(trim($v['D']))) {
                $flag = FALSE;
                $str .= '第'.$k.'行 出库时间 格式不正确,导入失败'."<br/>";
            }
            if ($v['E'] == '') {
                $flag = FALSE;
                $str .= '第'.$k.'行 储位 为空,导入失败'."<br/>";
            }
            if ($v['G'] == '') {
                $flag = FALSE;
                $str .= '第'.$k.'行 站点 为空,导入失败'."<br/>";
            } else {
                $site_id = $sites_arr[strtoupper(trim($v['G']))];
                if (!$site_id) {
                    $flag = FALSE;
                    $str .= '第'.$k.'行 站点:'.$v['G'].' 未启用或不存在,导入失败'."<br/>";
                }
                $v['G'] = $site_id;
            }
            if ($v['H'] == '') {
                $flag = FALSE;
                $str .= '第'.$k.'行 公司主体 为空,导入失败'."<br/>";
            } else {
                $CompanyId = PublicInfoService::getCompanyId($v['H']);
                if (!$CompanyId) {
                    $flag = FALSE;
                    $str .= '第'.$k.'行 公司主体:'.$v['H'].' 输入有误,导入失败'."<br/>";
                }
                $v['H'] = $CompanyId;
            }
            if ($v['I'] == '') {
                $flag = FALSE;
                $str .= '第'.$k.'行 是否退税 为空,导入失败'."<br/>";
            } else {
                $if = $v['I'] == '出口退税'?1:($v['I'] == '非出口退税'?0:'');
                if ($if === '') {
                    $flag = FALSE;
                    $str .= '第'.$k.'行 是否退税:'.$v['I'].' 输入有误,导入失败'."<br/>";
                }
                $v['I'] = $if;
            }
        }
        foreach ($datas as $k1 => $v1) { //储位相同+数量+出库类型+sku+时间+备注+站点   不能完全一样
            foreach ($datas as $k2 => $v2) {
                if ($k1 >= $k2) {
                    continue;
                }
                if ($v1['A'] == $v2['A'] && $v1['B'] == $v2['B'] && $v1['C'] == $v2['C'] && $v1['D'] == $v2['D']
                    && $v1['E'] == $v2['E'] && $v1['F'] == $v2['F'] && $v1['G'] == $v2['G'] && $v1['H'] == $v2['H']
                    && $v1['I'] == $v2['I']) {//储位相同
                    $flag = FALSE;
                    $str .= '第'.$k1.'行与第'.$k2.'行信息一致,请不要重复导入'."<br/>";
                }
            }
        }
        return array (
            'status'  => $flag,
            'message' => $str
        );
    }

    /**
     * 校验日期格式是否正确
     * @param string $date    日期
     * @param string $formats 需要检验的格式数组
     * @return boolean
     */
    public function check_date_isValid ($date, $formats = array (
        "Y-m-d",
        "Y/m/d"
    )) {
        $unixTime = strtotime($date);
        if (!$unixTime) { //strtotime转换不对，日期格式显然不对。
            return FALSE;
        }

        //校验日期的有效性，只要满足其中一个格式就OK
        foreach ($formats as $format) {
            if (date($format, $unixTime) == $date) {
                return TRUE;
            }
        }
        return FALSE;
    }

    /**
     * @param $arr -导入文件数组
     * @return string
     */
    public function upload_platform ($arr) {
        $data_info = array ();
        foreach ($arr as $key => $value) {
            if ($key == 1) {
                continue;
            } else {
                $sku_info = $this->load_sku_info($value['B']);
                //$supplier_info = D('StockIn','Service')->get_supplier_by_sku(array('sku' => $value['B']));
                $stockOutdata = array (
                    'type'                => trim($value['A']),
                    'sku'                 => strtoupper(trim($value['B'])),
                    'quantity'            => trim($value['C']),
                    'delivery_date'       => trim($value['D']),
                    'storage_position'    => trim($value['E']),
                    'remark'              => trim($value['F']),
                    'site_id'             => trim($value['G']),
                    'enterprise_dominant' => trim($value['H']),
                    'export_tax_rebate'   => trim($value['I']),
                    'op_time'             => $this->nowtime,
                    'delivery_man'        => $_SESSION['current_account']['id'],

                    'sku_name'               => $sku_info['sku_name'],
                    'sku_standard'           => $sku_info['sku_standard'],

                    //先不做
                    'internationalship_cost' => '',
                    'delivery_department'    => '',
                    //帐号 需要将帐号名转换成
                    'shipmentid'             => '',
                    'package_box_id'         => '',
                    'fnsku'                  => '',
                    'hs_code'                => '',
                    'declaration_element'    => '',
                );
            }
            $data_info[] = $stockOutdata;
        }
        return $this->create_deliveryorders($data_info);
    }


    /**
     * 出库明细页面
     */
    public function delivery_details ($_array = array (), $flag = TRUE) {
        $_array = empty($_array)?$_GET:$_array;
        $model  = $this->stockOut->get_deliveryorders_model($_array, $flag);
        if ($flag) {
            $Recieve_details = clone $model;
            $this->count     = $Recieve_details->count();//数量
            $Page            = new \Org\Util\Page($this->count, 20);// 实例化分页类 传入总记录数和每页显示的记录数(5)
            $this->page      = $Page->show();// 分页显示输出

            $model->order("delivery_date desc")
                ->limit($Page->firstRow.','.$Page->listRows);
        }
        // 进行分页数据查询 注意limit方法的参数要使用Page类的属性
        $result = $model->select();
        $result = $this->format_delivery_details_data($result);
        return $result;
    }

    /**
     * 格式化数据
     */
    public function format_delivery_details_data ($data) {
        $type_arr    = PublicdataService::get_deliveryorders_type();
        $company_arr = PublicInfoService::get_company_array();
        $sites       = PublicInfoService::get_site_array();
        //格式化
        foreach ($data as &$_data) {
            $_data['enterprise_dominant'] = $company_arr[$_data['enterprise_dominant']];
            $_data['delivery_man']        = PublicInfoService::get_user_name_by_id($_data['delivery_man']);
            $_data['seller_id']           = PublicInfoService::get_user_name_by_id($_data['seller_id']);
            $_data['type']                = $type_arr[$_data['type']];
            $_data['export_tax_rebate']   = $_data['export_tax_rebate'] == 1?'出口退税':'非出口退税';
            $_data['site_id']             = $sites[$_data['site_id']];
        }
        return $data;
    }
}